package com.valenx.distributedmulticamerasystem.utils;

import com.valenx.distributedmulticamerasystem.ResourceTable;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;
import ohos.distributedschedule.interwork.DeviceInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

//设备工具类
public class DeviceUtil {
//=============================================================================================================

    //设备适配器
    public static class DevicesItemProvider extends BaseItemProvider {
        private static final int SUBSTRING_START = 0;//子串开始位置

        private static final int SUBSTRING_END = 4;//子串结束位置

        private List<DeviceInfo> deviceInfoList;

        private Context context;

        private final int checkNum;

        public DevicesItemProvider(List<DeviceInfo> deviceInfoList, Context context,int checkNum) {
            this.deviceInfoList = deviceInfoList;
            this.context = context;
            this.checkNum = checkNum;
        }
//-------------------------------------------------------------------------------------------------------------

        //获取列表设备数量
        @Override
        public int getCount() {
            return deviceInfoList == null ? 0 : deviceInfoList.size();
        }
//-------------------------------------------------------------------------------------------------------------

        //获取对应的deviceInfo
        @Override
        public Object getItem(int position) {
            return Optional.of(deviceInfoList.get(position));
        }
//-------------------------------------------------------------------------------------------------------------

        //返回某一项的ID
        @Override
        public long getItemId(int position) {
            return position;
        }
//-------------------------------------------------------------------------------------------------------------

        //获取显示的设备项（Item）
        @Override
        public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
            Component deviceLayout;//设备项

            //如果有要销毁的项（回收利用）
            if (convertComponent != null) {
                deviceLayout = convertComponent;
            }
            //如果没有要销毁的项（新建）
            else {
                deviceLayout = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item_device_list, null, false);
            }

            //设置布局中设备ID和设备名称的文本对象
            Text devicesId = deviceLayout.findComponentById(ResourceTable.Id_device_id);
            Text devicesName = deviceLayout.findComponentById(ResourceTable.Id_device_name);
            Checkbox deviceCheckBox = deviceLayout.findComponentById(ResourceTable.Id_device_checkbox);

            //多选时显示多选框
            if (checkNum != 1){
                deviceCheckBox.setEnabled(true);
                deviceCheckBox.setVisibility(Component.VISIBLE);
            }

            //获取完整设备ID
            String deviceIdFull = deviceInfoList.get(position).getDeviceId();
            //隐藏ID中间部分
            String deviceIdPart = deviceIdFull.substring(SUBSTRING_START, SUBSTRING_END) + "******" + deviceIdFull.substring(deviceIdFull.length() - SUBSTRING_END);
            devicesId.setText(deviceIdPart);//设置布局中显示的设备ID
            devicesName.setText(deviceInfoList.get(position).getDeviceName());//设置布局中显示的设备名称
            deviceCheckBox.setChecked(false);//设置多选框为未选中

            return deviceLayout;//返回设备项
        }
    }
//=============================================================================================================

    //设备选择弹框
    public static class SelectDeviceDialog {
        private static final int DIALOG_WIDTH = 840;//弹框宽

        private static final int DIALOG_HEIGHT = 900;//弹框高

        private CommonDialog commonDialog;//弹框对象

        private int checkedNum = 0;//已选中数量

        private ListContainer devicesListContainer;


        public SelectDeviceDialog(Context context, List<DeviceInfo> deviceInfoList, int checkNum, SelectDeviceDialog.SelectResultListener listener) {
            if (checkNum == 1) {
                singleCheck(context, deviceInfoList, listener,checkNum);
            } else if (checkNum == 2) {
                doubleCheck(context, deviceInfoList, listener,checkNum);
            }
        }
//-------------------------------------------------------------------------------------------------------------

        //单选
        private void singleCheck(Context context, List<DeviceInfo> deviceInfoList, SelectDeviceDialog.SelectResultListener listener, int checkNum) {
            //创建设备弹框
            commonDialog = new CommonDialog(context);
            commonDialog.setAlignment(LayoutAlignment.CENTER);//居中
            commonDialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);//设置宽高
            commonDialog.setAutoClosable(true);//设置自动关闭
            Component dialogLayout = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_dialog_select_device, null, false);
            commonDialog.setContentCustomComponent(dialogLayout);//添加弹框布局


            //创建设备列表
            if (dialogLayout.findComponentById(ResourceTable.Id_listcontainer_devices) instanceof ListContainer) {
                ListContainer devicesListContainer = dialogLayout.findComponentById(ResourceTable.Id_listcontainer_devices);
                devicesListContainer.setReboundEffect(true);
                DevicesItemProvider devicesItemProvider = new DevicesItemProvider(deviceInfoList, context,checkNum);
                devicesListContainer.setItemProvider(devicesItemProvider);
                //创建设备选择事件监听器
                devicesListContainer.setItemClickedListener((listContainer, component, position, id) -> {
                    List<DeviceInfo> checkedDeviceInfoList = new ArrayList<>();
                    checkedDeviceInfoList.add(deviceInfoList.get(position));
                    listener.callBack(checkedDeviceInfoList);
                    commonDialog.hide();
                });
            }

            //点击弹框上的“取消”，隐藏弹框
            dialogLayout.findComponentById(ResourceTable.Id_cancel).setClickedListener(component -> commonDialog.hide());
        }
//-------------------------------------------------------------------------------------------------------------

        //双选
        private void doubleCheck(Context context, List<DeviceInfo> deviceInfoList, SelectDeviceDialog.SelectResultListener listener, int checkNum) {
            //创建设备弹框
            commonDialog = new CommonDialog(context);
            commonDialog.setAlignment(LayoutAlignment.CENTER);//居中
            commonDialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);//设置宽高
            commonDialog.setAutoClosable(true);//设置自动关闭
            Component dialogLayout = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_dialog_select_device, null, false);
            Text confirm = dialogLayout.findComponentById(ResourceTable.Id_cancel);
            confirm.setText("确认");
            commonDialog.setContentCustomComponent(dialogLayout);//添加弹框布局

            //创建设备列表
            if (dialogLayout.findComponentById(ResourceTable.Id_listcontainer_devices) instanceof ListContainer) {
                devicesListContainer = dialogLayout.findComponentById(ResourceTable.Id_listcontainer_devices);
                devicesListContainer.setReboundEffect(true);
                DevicesItemProvider devicesItemProvider = new DevicesItemProvider(deviceInfoList, context,checkNum);
                devicesListContainer.setItemProvider(devicesItemProvider);
                //创建设备选择事件监听器
                devicesListContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
                    @Override
                    public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                        Checkbox deviceCheckBox = component.findComponentById(ResourceTable.Id_device_checkbox);
                        //选中颜色
                        ShapeElement backgroundColorChecked = new ShapeElement();
                        backgroundColorChecked.setRgbColor(new RgbColor(220, 220, 220));
                        //未选中颜色
                        ShapeElement backgroundColorEmpty = new ShapeElement();
                        backgroundColorEmpty.setRgbColor(new RgbColor(238, 238, 238));
                        //设置选中状态及颜色
                        if (!deviceCheckBox.isChecked() && checkedNum < 2) {
                            deviceCheckBox.setChecked(true);
                            checkedNum++;
                            component.setBackground(backgroundColorChecked);
                        } else if (deviceCheckBox.isChecked() && checkedNum > 0) {
                            deviceCheckBox.setChecked(false);
                            checkedNum--;
                            component.setBackground(backgroundColorEmpty);
                        }
                    }
                });
            }

            //点击弹框上的“确认”
            confirm.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    if (checkedNum<2){
                        ToastUtil.showToast(context,"请选择2台设备");
                    }else {
                        List<DeviceInfo> checkedDeviceInfoList = new ArrayList<>();
                        //遍历ListContainer，找出所有被选中的项加入列表
                        for (int i = 0; i < devicesListContainer.getItemProvider().getCount(); i++) {
                            Component deviceLayout = devicesListContainer.getComponentAt(i);
                            Checkbox deviceCheckBox = deviceLayout.findComponentById(ResourceTable.Id_device_checkbox);
                            if (deviceCheckBox.isChecked()) {
                                checkedDeviceInfoList.add(deviceInfoList.get(i));
                            }
                        }
                        if (checkedDeviceInfoList != null && !checkedDeviceInfoList.isEmpty()) {
                            listener.callBack(checkedDeviceInfoList);
                            commonDialog.hide();
                        }
                    }

                }
            });
        }
//-------------------------------------------------------------------------------------------------------------

        public void show() {
            commonDialog.show();
        }
//-------------------------------------------------------------------------------------------------------------

        public interface SelectResultListener {
            void callBack(List<DeviceInfo> checkedDeviceInfoList);
        }
    }
}
